<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-12-15 16:17:34
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
    <div class="comparison">
        <!-- <nutbTitle title="数据对比"></nutbTitle> -->
        <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
            :buttons="fyButtons">
            <NuformItem label="日期" prop="dataTime" width="100%" style="display: block;">
                <el-date-picker v-model="formData.dataTime" type="datetimerange" style="width: 420px;"
                    value-format="yyyy-MM-dd HH:mm:ss" :clearable="false" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
            </NuformItem>
            <div class="btnBox">
                <nu-button type="primary" class="searchButton" @click="searchLine">查询</nu-button>
                <!-- <nu-button class="searchButton" @click="clearParams">清除</nu-button> -->
            </div>
        </NuVerifyForm>
        <div class="line"></div>
        <nu-row class="row" :gutter="20">
            <nu-col :span="6" style="height: 100%;">
                <nuTree v-model="currentLivingObj.id" :options="treeData" :props="defaultProps"
                    @onClickNode="handleNodeClick" :checkedKeys="checkedKeys" @checkChange="handleCheckChange" ref="nuTree">
                </nuTree>
            </nu-col>
            <nu-col :span="18" style="height: 100%;overflow: hidden;">
                <div style="height:calc(100vh - 220px - 210px)">
                    <nu-echarts width="auto" height="100%" :option="lineOption" class="echarts"
                        v-if="isEchart"></nu-echarts>
                </div>
                <div style="height:30%">
                    <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options">
                    </NuTableList>
                </div>
            </nu-col>
        </nu-row>
    </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue"
import nutbTitle from "@/components/base/tableTitle.vue"
import nuEcharts from "@/components/base/echarts"
import NuVerifyForm from "@/components/verify-form"
import NuformItem from "@/components/verify-form/form-item.vue"
import nuInput from "@/components/base/input"
import nuSelect from "@/components/base/select"
import nuButton from "@/components/base/button"
import NuTableList from "@/components/tableList/TableFormList"
import nuSelectTree from "@/components/base/selectTree"
import nuRow from "@/components/base/row.vue";
import nuTree from "@/components/base/tree";
import * as echarts from 'echarts';
import { getDateTime } from "@/utils/ruoyi";
export default {
    name: "comparison",
    components: { nuCol, nutbTitle, nuEcharts, NuVerifyForm, NuformItem, nuInput, nuSelect, nuButton, NuTableList, nuSelectTree, nuRow, nuTree },
    data() {
        return {
            formData: { dataTime: [] },
            fyButtons: [],
            isEchart: true,
            lineOption: {
                // color: ['#40b0e2', '#69e5c1', '#626b90', '#a0a7e5'],
                color: [
                    '#40b0e2', '#5470c6', '#69e5c1', '#91cc75', '#626b90', '#fac858', '#a0a7e5', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc',
                    "#516b91", "#59c4e6", "#edafda", "#93b7e3", "#a5e7f0", "#cbb0e3"
                ],
                title: {
                    text: '数据对比曲线',
                    left: '0',
                    textStyle: {
                        fontWeight: "normal"
                    },
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                    },
                },
                xAxis: {
                    type: 'category',
                    data: [],
                },
                yAxis: {
                    type: 'value',
                    name: '',
                },
                grid: {
                    left: '5%',
                    right: '3%',
                },
                series: [],
            },
            seriesColor: [['rgba(64, 176, 226,0.8)', 'rgba(64, 176, 226,0.1)'], ['rgba(105, 229, 193,0.8)', 'rgba(105, 229, 193,0.1)']],
            dataSource: [],
            columns: [],
            options: {
                'default-expand-all': true,
                'element-loading-background': 'rgba(225,239,242)',
                'element-loading-text': '数据正在加载中',
                'row-key': 'pid',
                'header-cell-style': {
                    background: 'rgba(105, 159, 209, 0.7)',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontsize: '16px',
                },
                isNoSetHeight: true,
                height: '190px',
            },
            treeData: [],
            // 数据默认字段
            defaultProps: {
                parent: 'parentId',   // 父级唯一标识
                value: 'id',          // 唯一标识
                label: 'name',       // 标签显示
                children: 'children', // 子级
                showCheckbox: true,
                renderContent: this.renderContent,
                defaultExpandAll: false,
                defaultExpandedKeys: []
            },
            currentLivingObj: { id: "" },
            selectTreeColumns: [
                { label: '对比项1', value: '' },
                { label: '对比项2', value: '' },
            ],
            checkedKeys: [],
            treeCheckedKeys: []
        };
    },
    created() {
    },
    mounted() {
        this.formData.dataTime = [getDateTime('day') + ' 00:00:00', getDateTime('day') + ' 23:59:59']
        this.getTreeData()
    },
    methods: {
        /**
         * 查询
         */
        searchLine() {
            this.$refs['formData'].searchForm('form');
        },
        /**
         * form组件内置查询事件
         */
        searchForm(val) {
            if (val) {
                this.getComparison();
            }
        },
        /**
         * 添加对比项
         */
        searchPlusClick() {
            if (this.selectTreeColumns.length > 3) {
                this.$message({
                    type: 'info',
                    message: '超出最大可对比项'
                });
                return false
            }
            this.selectTreeColumns.push({ label: '对比项' + (this.selectTreeColumns.length + 1), value: '' })
        },
        /**
         * 清除数据
         */
        clearParams() {
            this.resetForm('formData')
        },
        /**
         * 重置表单
         */
        resetForm(formName) {
            this.$refs[formName].resetForm('form');
            for (let k in this[formName]) {
                if (Object.prototype.toString.call(this[formName][k]) == "[object String]") {
                    this[formName][k] = ''
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Array]") {
                    this[formName][k] = []
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Number]") {
                    this[formName][k] = ''
                }
            }
        },
        // 复选
        handleCheckChange(data, checked) {
            if (checked.checkedNodes.length) {
                this.treeCheckedKeys = this.unique(this.getLastChild({ children: checked.checkedNodes }))
                this.getComparison()
            } else {
                this.dataSource = []
                this.lineOption.series = []
                this.treeCheckedKeys = []
                this.isEchart = false
                this.$nextTick(() => {
                    this.isEchart = true
                })
            }
        },
        /**
         * 数组去重
         * @param {*} arr 
         */
        unique(arr) {
            return Array.from(new Set(arr));
        },
        /**
         * 获取最后一级
         * @param {*} node 
         */
        getLastChild(node) {
            let arr = []
            function x(node) {
                if (node.children && node.children.length) {
                    for (let i = 0, len = node.children.length; i < len; i++) {
                        x(node.children[i])
                    }
                } else {
                    arr.push(node.modelId)
                }
                return arr
            }
            x(node)
            return arr
        },
        /**
         * 获取曲线数据
         */
        getComparison() {
            // let ids = this.selectTreeColumns.map(item => { return item.value })
            let ids = this.treeCheckedKeys
            if (ids.length < 1) {
                this.$message({
                    type: 'info',
                    message: '请选择对比项'
                });
                return false
            }
            let postData = {
                // ...this.formData,
                meterIds: ids ? ids.join(',') : '',
                startDay: this.formData.dataTime[0],
                endDay: this.formData.dataTime[1],
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.columns = [{
                label: '',
                prop: 'name',
                width: '220px',
                show: true
            }]
            this.dataSource = []
            this.lineOption.series = []
            this.$httpGet(window.api.getComparison, postData).then(res => {
                if (res.code == 200) {
                    res.energyCharts = res.energyCharts.filter(item=> item?.meterName)
                    console.log(res.energyCharts)
                    this.isEchart = false
                    let xAxis = []
                    this.lineOption.xAxis.data = res.energyCharts[0].xaxis
                    this.lineOption.tooltip.formatter = (params) => {
                        let str = ''
                        params.forEach((item, i) => {
                            if (i == 0) {
                                str += `${item.name}<br/>`
                            }
                            let unit = item.data.unit ? `（${item.data.unit}）` : ''
                            str += `<div style='display: flex;align-items: center;'>${item.marker} <div style='display: flex;'>
                                <span>${item.seriesName}</span>：<span > ${item.value}</span> ${unit}<br/></div></div>
                            `
                        })
                        return str
                    }
                    res.energyCharts.forEach((item, i) => {
                        let obj = {};
                        item.tableDatas.forEach((item2, i2) => {
                            if (i == 0) {
                                this.columns.push({
                                    label: item2.time,
                                    prop: item2.time,
                                })
                            }
                            obj[item2.time] = item2.energy
                        })
                        let unit = item.unit ? `（${item.unit}）` : ''
                        obj['name'] = item.meterName + unit
                        this.dataSource.push(obj)
                        this.lineOption.series.push({
                            name: item.meterName,
                            data: item.energys.map(v => { return { value: v, unit: item.unit } }),
                            unit: item.unit,
                            type: 'line',
                            showAllSymbol: true,
                            symbolSize: 0,
                            smooth: false,
                            // areaStyle: {
                            // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            //     {
                            //         offset: 0,
                            //         color: this.seriesColor[i][0],
                            //     },
                            //     {
                            //         offset: 1,
                            //         color: this.seriesColor[i][1],
                            //     },
                            // ]),
                            // },
                        })
                    })

                    this.lineOption.title.text = '数据对比曲线'
                    this.$nextTick(() => {
                        this.isEchart = true
                    })
                } else {
                    this.dataSource = []
                }
            }).catch(err => {
                this.dataSource = []
            });
        },
        /**
         * tree节点单击
         */
        handleNodeClick(item, data) {
            this.currentLivingObj = item;
            this.currentLivingObj["level"] = data.level;
        },
        //获取树形控件
        getTreeData() {
            this.defaultProps.defaultExpandedKeys = []
            this.$httpGet(window.api.getTreeData).then(res => {
                if (res.code == 200) {
                    this.treeData.push(res)
                    res.children.forEach(item => {
                        this.defaultProps.defaultExpandedKeys.push(item.id)
                    })
                } else {
                }
            }).catch(err => {

            });
        },
        renderContent(h, { node, data, store }) {
            if (node.level == 3 && data.online == 1) {
                return (
                    <span class="custom-tree-node mainChannel">
                        <span>{node.label}</span>
                    </span>);
            } else {
                return (
                    <span class="custom-tree-node">
                        <span>{node.label}</span>
                    </span>);
            }
        }
    }
};
</script>
    
<style scoped lang="scss">
.comparison {
    height: 100%;
}

.searchForm {
    // height: calc(100% - 40px);
    display: flex;
    align-items: center;
    position: relative;
    flex-wrap: wrap;
}

.btnBox {
    display: flex;
    float: right;
    z-index: 10;
    position: absolute;
    top: 15px;
    right: 10px;
}

.row {
    height: calc(100% - 90px);
    width: 100%;
}

.searchPlusButton {
    border-radius: 50% !important;
    margin: 0 15px;
}

.lineDes {
    color: #409EFF;
    font-size: 14px;
    position: absolute;
    top: 0;
    z-index: 1;
    left: 40px;
}

::v-deep .mainChannel {
    color: rgba(72, 118, 255, 1);
}
</style>
    
    